package com.tql.mall.merchant.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.tql.mall.common.result.R;
import com.tql.mall.common.util.AuthContextHolder;
import com.tql.mall.merchant.service.LogisInfoService;
import com.tql.mall.merchant.service.ReturnInfoService;
import com.tql.mall.model.enums.ReturnStateEnum;
import com.tql.mall.model.order.ReturnInfo;
import com.tql.mall.order.client.OrderFeignClient;
import io.swagger.annotations.Api;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

@RestController
@RequestMapping("/merchant/returnInfo")
@Api("退单信息相关接口")
public class ReturnInfoController {



    @Autowired
    private OrderFeignClient orderFeignClient;

    @Autowired
    private ReturnInfoService returnInfoService;

    @Autowired
    private LogisInfoService logisInfoService;



    @PostMapping("updateStatus/{flag1}")
    public R<Void> updateStatus(@RequestBody ReturnInfo returnInfo, @PathVariable Integer flag1){
        if (flag1 != ReturnStateEnum.RETURN_SUCCESS.getCode() && flag1 !=ReturnStateEnum.RETURN_FAIL.getCode()) return R.fail();
        int flag = 3;
        if (flag1 == ReturnStateEnum.RETURN_SUCCESS.getCode()){//同意
            flag = 4;
        }else {//不同意
            flag = 5;
        }
        //更新订单状态[order_info]
        orderFeignClient.updateOrderStatus(returnInfo.getOrderId(),flag);
        //更新退单状态
        returnInfo.setUpdateTime(new Date());
        returnInfo.setState(flag1);
        returnInfoService.updateById(returnInfo);

        return R.ok();
    }

    @GetMapping("{page}/{limit}")
    public R<Map<String,Object>> getReturnPage(@PathVariable Integer page, @PathVariable Integer limit , Long shopId){

        IPage<ReturnInfo> page1 = new Page<>(page,limit);
        QueryWrapper<ReturnInfo> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("shop_id",shopId);
        returnInfoService.page(page1,queryWrapper);
        HashMap<String,Object> map = new HashMap<>();
        map.put("total",page1.getTotal());
        map.put("record",page1.getRecords());
        return R.ok(map);
    }


    @PostMapping("returnGood")
    private R<Void> returnGood(@RequestBody ReturnInfo returnInfo, HttpServletRequest req) {
        // 设置用户ID
        String userId = AuthContextHolder.getUserId(req);
        returnInfo.setUserId(Long.parseLong(userId));
        // 退货
        returnInfoService.returnGood(returnInfo);
        return R.ok();
    }



}
